<template>
  <div class="xtx-pagination">
    <a v-if="myCurrentPage===1" href="javascript:;" class="disabled">上一页</a>
    <a v-else href="javascript:;" @click=changePager(myCurrentPage-1)>上一页</a>
    <span v-if="pager.start>1">...</span>
    <a href="javascript:;" @click=changePager(i) :class="{active:i===myCurrentPage}" v-for="i in pager.btnArr"
      :key="i">{{i}}</a>
    <span v-if="pager.end<pager.pageCount">...</span>
    <a v-if="myCurrentPage===pager.pageCount" href="javascript:;" class="disabled">下一页</a>
    <a v-else href="javascript:;" @click=changePager(myCurrentPage+1)>下一页</a>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'

export default {
  name: 'XtxPageination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },
  setup(props, { emit }) {
    const count = 5 // 显示按钮个数
    const myCurrentPage = ref(1) // 当前显示页码
    const myTotal = ref(100) // 渲染数据总条数
    const myPageSize = ref(10) // 每页显示条数
    const pager = computed(() => {
      const pageCount = Math.ceil(myTotal.value / myPageSize.value) // 按钮总个数（总页数）
      const offset = Math.floor(count / 2)
      let start = myCurrentPage.value - offset
      let end = start + count - 1
      if (start < 1) {
        start = 1
        end = (start + count - 1) > pageCount ? pageCount : (start + count - 1)
      }
      if (end > pageCount) {
        end = pageCount
        start = (end - count + 1) < 1 ? 1 : (end - count + 1)
      }
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return {
        pageCount,
        btnArr,
        start,
        end
      }
    })

    // 监听props传入数据的变化
    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })

    const changePager = (page) => {
      myCurrentPage.value = page
      emit('current-page', myCurrentPage)
    }

    return { myCurrentPage, pager, changePager }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;

  >a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;

    &:hover {
      color: @xtxColor;
    }

    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;

      &:hover {
        color: #333
      }
    }
  }

  >span {
    margin-right: 10px;
  }
}
</style>
